<?php
include_once 'database/db.php';
include $_SERVER['DOCUMENT_ROOT']."/lib/spyc.php";
class FileJoin
{
    private $filepath; //上传目录
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    private $host;
    // private $DB; // mongodb数据库驱动

    public function __construct($fileName, $totalBlobNum)
    {
        $ENV = spyc_load_file($_SERVER['DOCUMENT_ROOT'].'/properties/env.yml');
        $this->fileName = $fileName;
        $this->totalBlobNum = $totalBlobNum;
        $this->filepath=($ENV['upload']['path'])['0'];
        $this->filepath = $this->filepath.DIRECTORY_SEPARATOR.sha1($this->fileName);
        $this->host = ($ENV['upload']['host'])['0'];
        // $this->DB = new DB();
    }

    public function join()
    {
        $fileStore = fopen($this->filepath.DIRECTORY_SEPARATOR.$this->fileName, 'ab+');
        for ($i=1; $i<= $this->totalBlobNum; $i++) {
            $filename = $this->filepath.DIRECTORY_SEPARATOR.$this->fileName.'__'.$i;
            $handle = fopen($filename, rb);
            fwrite($fileStore, fread($handle, filesize($filename)));
            fclose($handle);
        }
        fclose($fileStore);
        $this->deleteFileBlob();
    }

    //删除文件块
    private function deleteFileBlob()
    {
        for ($i=1; $i<= $this->totalBlobNum; $i++) {
            @unlink($this->filepath.DIRECTORY_SEPARATOR. $this->fileName.'__'.$i);
        }
    }

    public function getDownloadURL()
    {
        return 'http://'.$this->host.':92/fileshare'.$this->filepath.DIRECTORY_SEPARATOR.$this->fileName;
    }
}

@$filename = $_POST['file_name'];
@$totalBlobNum = $_POST['total_blob_num'];
$data = [];
if (!$filename || !$totalBlobNum) {
    $data['code']=0;
    $data['msg']='参数不完整';
} else {
    $filejoin = new FileJoin($filename, $totalBlobNum);
    $filejoin->join();
    $data['code']=1;
    $data['downloadURL']=$filejoin->getDownloadURL();
}

echo json_encode($data);
